<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>文件上传表单</title>
</head>
<body>
<h1>文件上传表单</h1>
<form id="uploadForm">
  <label for="directory">上传的文件目录:</label>
  <input type="text" id="directory" name="directory" required><br><br>

  <label for="filename">上传后的文件名:</label>
  <input type="text" id="filename" name="filename" required><br><br>

  <label for="file">上传文件:</label>
  <input type="file" id="file" name="file" required><br><br>

  <button type="button" onclick="uploadFile()">确定</button>
</form>

<script>
  async function uploadFile() {
    const directoryInput = document.getElementById('directory');
    const filenameInput = document.getElementById('filename');
    const fileInput = document.getElementById('file');

    // 去除输入值的前后空格
    const directory = directoryInput.value.trim();
    const filename = filenameInput.value.trim();
    const file = fileInput.files[0];

    // 检查 filename 和 file 是否为空
    if (!filename) {
      alert('上传后的文件名不能为空');
      return;
    }

    if (!file) {
      alert('请上传文件');
      return;
    }

    const formData = new FormData();
    formData.append('directory', directory);
    formData.append('filename', filename);
    formData.append('file', file);

    try {
      const response = await fetch('http://localhost:8080/api/land/upload_file', {
        method: 'POST',
        body: formData
      });

      if (response.ok) {
        const result = await response.json();
        alert('文件上传成功: ' + result.response);
      } else {
        alert('文件上传失败');
      }
    } catch (error) {
      console.error('Error during fetch:', error);
      alert('文件上传过程中出现错误');
    }
  }
</script>
</body>
</html>
